//
//  NSCalendar+YCTools.m
//  Pods
//
//  Created by Apple on 2023/4/29.
//

#import "NSCalendar+YCTools.h"

@implementation NSCalendar (YCTools)

- (NSDate *)yc_startOfDayForDate:(NSDate*)date {
    if (![self respondsToSelector:@selector(startOfDayForDate:)]) {
        NSDateComponents* comps = [self components:NSCalendarUnitYear | NSCalendarUnitMonth |NSCalendarUnitDay fromDate:date];
        return [self dateFromComponents:comps];
    }
    return [self startOfDayForDate:date];
}

- (NSDate *)yc_nextStartOfDay:(NSInteger)nNext forDate:(NSDate *)date {
    NSDate *firstDay = [self yc_startOfDayForDate:date];
    NSDateComponents *comp = [NSDateComponents new];
    comp.day = nNext;
    return [self dateByAddingComponents:comp toDate:firstDay options:0];
}

- (NSDate *)yc_startOfUnit:(NSCalendarUnit)unit forData:(NSDate *)date {
    NSDate *firstDay = nil;
    [self rangeOfUnit:unit startDate:&firstDay interval:NULL forDate:date];
    return firstDay;
}

- (NSDate *)yc_startOfYearForDate:(NSDate*)date {
    return [self yc_startOfUnit:NSCalendarUnitYear forData:date];
}

- (NSDate *)yc_startOfMonthForDate:(NSDate*)date {
    return [self yc_startOfUnit:NSCalendarUnitMonth forData:date];
}

- (NSDate *)yc_nextStartOfMonth:(NSInteger)nNext forDate:(NSDate *)date {
    NSDate *firstDay = [self yc_startOfMonthForDate:date];
    NSDateComponents *comp = [NSDateComponents new];
    comp.month = nNext;
    return [self dateByAddingComponents:comp toDate:firstDay options:0];
}

- (NSInteger)yc_firstWeekdayInThisMotnth:(NSDate *)date {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar setFirstWeekday:2];
    NSDateComponents *comp = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:date];
    [comp setDay:1];
    NSDate *firstDayOfMonthDate = [calendar dateFromComponents:comp];
    NSUInteger firstWeekday = [calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfMonth forDate:firstDayOfMonthDate];
    return firstWeekday;
}

//  当前月有多少天
- (NSInteger)yc_daysOfMonthForDate:(NSDate *)date {
    return [self rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date].length;
}

- (NSInteger)yc_weeksOfMonthForDate:(NSDate *)date {
    NSInteger days = [self rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date].length;
    NSInteger firstDayWeek = [[self components:NSCalendarUnitWeekday fromDate:date] weekday];
    firstDayWeek = (firstDayWeek - self.firstWeekday + 7) % 7;
    NSInteger week = (days + firstDayWeek + 6) / 7;
//    NSLog(@"%d", week);
    return week;
}

@end
